package com.spring.business.configure.controller;

import com.spring.business.configure.entity.FileInfo;
import com.spring.business.configure.service.IConfigureService;
import com.spring.module.file.FileItem;
import com.spring.module.file.IFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

/**
 * 上传下载
 *
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@RestController
@RequestMapping("/configure/file")
public class MinioController {

    @Autowired
    private IFileService fileService;
    @Resource
    IConfigureService iConfigureService;


    @GetMapping("/list")
    public Object listFiles(){

        return fileService.list();
    }

    @PostMapping("/delete")
    public void deleteFile(String fileCode){
        fileService.delete(fileCode);
    }

    @PostMapping("/upload")
    public String uploadFile(@RequestPart("file") MultipartFile file) {

        return iConfigureService.uploadFile(file);
    }

    @PostMapping("/download")
    public void download(HttpServletResponse response, String fileCode) throws IOException {

        //FileInfo fileInfo = iConfigureService.getFile(fileCode);
        InputStream inputStream =  fileService.download(fileCode);
        response.reset();
        response.setContentType("application/octet-stream");
        response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileCode, "UTF-8"));
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] b = new byte[1024];
        int len;
        //从输入流中读取一定数量的字节，并将其存储在缓冲区字节数组中，读到末尾返回-1
        while ((len = inputStream.read(b)) > 0) {
            outputStream.write(b, 0, len);
        }
        inputStream.close();
    }

}
